<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Python lists</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, data types, lists, slices, list comprehensions, learn Python">
<meta name="description" content="In this chapter of the Python tutorial, we
will work with Python lists.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Python lists</h1>

<p>
In this part of the Python programming tutorial, we will cover Python lists
in more detail.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
<b>Python list</b> is a mutable container. It can contain mixed types. 
A list is an ordered collection of values. It represents a mathematical 
concept of a finite sequence. Values of a list are called items or elements 
of the list. A list can contain the same value multiple 
times. Each occurrence is considered a distinct item.
</p>

<p>
List elements can be accessed by their index. The first element has 
index 0, the last one has index -1.
</p>


<pre class="code">
#!/usr/bin/python

nums = [1, 2, 3, 4, 5]
print nums
</pre>

<p>
This is a simple list having 5 elements. The list is delimited by 
square brackests []. The elements of a list are separated by comma 
character. The contents of a list are printed to the console. 
</p>

<pre>
$ ./simple.py
[1, 2, 3, 4, 5]
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
Lists can contain elements of various data types. 
</p>

<pre class="code">
#!/usr/bin/python

class Being:
    pass

objects = [1, -2, 3.4, None, False, [1, 2], "Python", (2, 3), Being(), {}]
print objects
</pre>

<p>
In the example, we create an objects list. It contains numbers, a boolean value,
another list, a string, a tuple, a custom object and a dictionary. 
</p>

<pre>
$ ./various_objects.py
[1, -2, 3.4, None, False, [1, 2], 'Python', (2, 3), &lt;__main__.Being 
  instance at 0xb76a186c&gt;, {}]
</pre>

<p>
Output.
</p>


<h2>List initialization</h2>

<p>
Sometimes we need to initialize a list in advance to 
have a particular number of elements. 
</p>

<pre class="code">
#!/usr/bin/python

n1 = [0 for i in range(15)]
n2 = [0] * 15

print n1
print n2

n1[0:11] = [10] * 10

print n1
</pre>

<p>
In this example we initialize two lists using
a list comprehension and a * operator. 
</p>

<pre class="explanation">
n1 = [0 for i in range(15)]
n2 = [0] * 15
</pre>

<p>
These two lists are initialized to 15 zeros. 
</p>

<pre class="explanation">
n1[0:11] = [10] * 10
</pre>

<p>
First ten values are replaced with 10s. 
</p>

<pre>
$ ./initialization.py
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0]
</pre>

<p>
Example output.
</p>


<h2>The list() function</h2>

<p>
The <code>list()</code> function creates a list from an iterable
object. An iterable may be either a sequence, a container that 
supports iteration, or an iterator object.  If no parameter is 
specified, a new empty list is created.
</p>

<pre class="code">
#!/usr/bin/python

a = []
b = list()

print a == b

print list((1, 2, 3))
print list("ZetCode")
print list(['Ruby', 'Python', 'Perl'])
</pre>

<p>
In the example, we create an empty list, a list from a tuple,
a string and another list. 
</p>

<pre class="explanation">
a = []
b = list()
</pre>

<p>
These are two ways to create an empty list. 
</p>

<pre class="explanation">
print a == b
</pre>

<p>
The line prints True. This confirms, that a, b are equal.
</p>

<pre class="explanation">
print list((1, 2, 3))
</pre>

<p>
We create a list from a Python tuple. 
</p>

<pre class="explanation">
print list("ZetCode")
</pre>

<p>
This line produces a list from a string. 
</p>

<pre class="explanation">
print list(['Ruby', 'Python', 'Perl'])
</pre>

<p>
Finally, we create a copy of a list of strings. 
</p>

<pre>
$ ./list.py
True
[1, 2, 3]
['Z', 'e', 't', 'C', 'o', 'd', 'e']
['Ruby', 'Python', 'Perl']
</pre>

<p>
Example output.
</p>


<h2>List operations</h2>

<p>
The following code shows some basic list operations. 
</p>

<pre class="code">
#!/usr/bin/python

n1 = [1, 2, 3, 4, 5]
n2 = [3, 4, 5, 6, 7]

print n1 == n2
print n1 + n2

print n1 * 3

print 2 in n1
print 2 in n2
</pre>

<p>
We define two lists of integers. We use a few operators on these lists.
</p>

<pre class="explanation">
print n1 == n2
</pre>

<p>
The contents of the lists are compared with the == operator. The line
prints False since the elements are different.
</p>

<pre class="explanation">
print n1 + n2
</pre>

<p>
The n1, n2 lists are added to form a new list. The new list has all
elements of both the lists. 
</p>

<pre class="explanation">
print n1 * 3
</pre>

<p>
We use the multiplication operator on the list. It repeats the elements
n times. 3 times in our case. 
</p>

<pre class="explanation">
print 2 in n1
</pre>

<p>
We use the <code>in</code> operator to find out, whether the value is present
in the list. It returns a boolean True or False. 
</p>

<pre>
$ ./lists.py
False
[1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
True
False
</pre>

<p>
Running the example.
</p>


<h2>Sequence functions</h2>

<p>
Sequence functions can be used on any sequence types, including lists.
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

print "There are %d items" % len(n)
print "Maximum is %d" % max(n)
print "Minimum is %d" % min(n)
print "The sum of values is %d" % sum(n)
</pre>

<p>
In the example above, we have four functions. The <code>len()</code>, <code>max()</code>,
<code>min()</code>, and <code>sum()</code> functions.
</p>

<pre class="explanation">
print "There are %d items" % len(n)
</pre>

<p>
The <code>len()</code> function returns the size of the list. The number of 
elements of the list. 
</p>

<pre class="explanation">
print "Maximum is %d" % max(n)
print "Minimum is %d" % min(n)
</pre>

<p>
The <code>max()</code> and <code>min()</code> functions return the maximum 
and the minimum of the list. 
</p>

<pre class="explanation">
print "The sum of values is %d" % sum(n)
</pre>

<p>
The <code>sum()</code> function calculates the sum of the numbers of the n list.
</p>

<pre>
$ ./functions.py
There are 8 items
Maximum is 8
Minimum is 1
The sum of values is 36
</pre>

<p>
Output.
</p>


<h2>Adding list elements</h2>

<p>
This section will show how elements are added to a Python list. 
</p>

<pre class="code">
#!/usr/bin/python

langs = list()

langs.append("Python")
langs.append("Perl")
print langs

langs.insert(0, "PHP")
langs.insert(2, "Lua")
print langs

langs.extend(("JavaScript", "ActionScript"))
print langs
</pre>

<p>
We have three methods to add new elements to a list. The <code>append()</code>,
the <code>insert()</code> and the <code>extend()</code> methods.
</p>

<pre class="explanation">
langs = list()
</pre>

<p>
An empty list is created using the built-in <code>list()</code> method.
</p>

<pre class="explanation">
langs.append("Python")
langs.append("Perl")
</pre>

<p>
The <code>append()</code> method adds an item at the end of the list.
We append two strings. 
</p>

<pre class="explanation">
langs.insert(0, "PHP")
langs.insert(2, "Lua")
</pre>

<p>
The <code>insert()</code> method places an element at a specific position
indicated by the index number. The "PHP" string is inserted at the first
position, the "Lua" string at the third position. Note that list index numbers
start from zero.
</p>

<pre class="explanation">
langs.extend(("JavaScript", "ActionScript"))
</pre>

<p>
The <code>extend()</code> method adds a sequence of values to the end
of a list. In our case two strings of a Python tuple are appended at
the end of our list. 
</p>

<pre>
$ ./adding.py
['Python', 'Perl']
['PHP', 'Python', 'Lua', 'Perl']
['PHP', 'Python', 'Lua', 'Perl', 'JavaScript', 'ActionScript']
</pre>

<p>
Example output. 
</p>


<h2>IndexError, TypeError</h2>

<p>
The <code>IndexError</code> is raised when a list subscript is out of range. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

try:

    n[0] = 10
    n[6] = 60
    
except IndexError, e:
    
    print e
</pre>

<p>
In the script we have defined a list of 5 integers. These elements have
indexes 0, 1, 2, 3 and 4. Using a bigger index leads to an error.
</p>

<pre class="explanation">
n[6] = 60
</pre>

<p>
Index 6 is out of range for our list. An <code>IndexError</code> is thrown.
</p>

<pre class="explanation">
except IndexError, e:
    
    print e
</pre>

<p>
We catch the error using the <code>except</code> clause. In the body of the
clause, we print the error message. 
</p>

<pre>
$ ./indexerror.py
list assignment index out of range
</pre>

<p>
Example output.
</p>

<hr class="btm">

<p>
If an index of a tuple is not a plain integer a <code>TypeError</code> 
is thrown. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

try:
    print n[1]
    print n['2']
    
except TypeError, e:
    print "Error in file %s" % __file__
    print "Message: %s" % e
</pre>

<p>
This example throws a <code>TypeError</code>.
</p>

<pre class="explanation">
print n['2']
</pre>

<p>
A list index must be an integer. Other types end in error.
</p>

<pre class="explanation">
except TypeError, e:
    print "Error in file %s" % __file__
    print "Message: %s" % e
</pre>

<p>
In the except block, we print the name of the file, where the
exception has occured and the message string.
</p>

<pre>
$ ./typeerror.py
2
Error in file ./typeerror.py
Message: list indices must be integers, not str
</pre>

<p>
Output of the script. 
</p>


<h2>Removing elements</h2>

<p>
Previously we have added items to a list. Now we will be removing them
from a list. 
</p>

<pre class="code">
#!/usr/bin/python

langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs

langs.pop(3)
langs.pop()
print langs

langs.remove("Ruby")
print langs
</pre>

<p>
The <code>pop()</code> method removes and returns an element with a specified index
or the last element, if the index number is not given.
The <code>remove()</code> method removes a particular item from a Python list. 
</p>

<pre class="explanation">
langs.pop(3)
langs.pop()
</pre>

<p>
We take away the element which has index 3. The second line removes and returns 
the last element from the list, namely "JavaScript" string. 
</p>

<pre class="explanation">
langs.remove("Ruby")
</pre>

<p>
This line removes a "Ruby" string from the langs list. 
</p>

<pre>
$ ./removing.py
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
['Python', 'Ruby', 'Perl']
['Python', 'Perl']
</pre>

<p>
From the ouput of the script we can see the effects of the described methods. 
</p>

<hr class="btm">

<p>
A <code>del</code> keyword can be used to delete list elements as well. 
</p>

<pre class="code">
#!/usr/bin/python

langs = ["Python", "Ruby", "Perl", "Lua", "JavaScript"]
print langs

del langs[1]
print langs

#del langs[15]

del langs[:]
print langs
</pre>

<p>
We have a list of strings. We use the <code>del</code> keyword to delete
list elements. 
</p>

<pre class="explanation">
del langs[1]
</pre>

<p>
We remove the second string from the list. It is the "Ruby" string.
</p>

<pre class="explanation">
#del langs[15]
</pre>

<p>
We can delete only existing elements. If we uncomment the code line, we will
receive an <code>IndexError</code> message.
</p>

<pre class="explanation">
del langs[:]
</pre>

<p>
Here we remove all the remaining elements from the list. The [:] characters
refer to all items of a list. 
</p>

<pre>
$ ./removing2.py
['Python', 'Ruby', 'Perl', 'Lua', 'JavaScript']
['Python', 'Perl', 'Lua', 'JavaScript']
[]
</pre>

<p>
Running the script.
</p>


<h2>Modifying elements</h2>

<p>
In the next example we will be modifying list elements.
</p>

<pre class="code">
#!/usr/bin/python

langs = ["Python", "Ruby", "Perl"]

langs.pop(2)
langs.insert(2, "PHP")
print langs

langs[2] = "Perl"
print langs
</pre>

<p>
In the example we modify the third element of the langs list twice.
</p>

<pre class="explanation">
langs.pop(2)
langs.insert(2, "PHP")
</pre>

<p>
One way to modify an element is to remove it and place a different 
element at the same position. 
</p>

<pre class="explanation">
langs[2] = "Perl"
</pre>

<p>
The other method is more straightforward. We assign a new element
at a given position. Now there is "Perl" string at the third position
again. 
</p>

<pre>
$ ./modify.py
['Python', 'Ruby', 'PHP']
['Python', 'Ruby', 'Perl']
</pre>

<p>
Output.
</p>


<h2>Copying lists</h2>

<p>
There are several ways how we can copy a list in Python. 
We will mention a few of them. 
</p>

<pre class="code">
#!/usr/bin/python

import copy

w = ["Python", "Ruby", "Perl"]

c1 = w[:]
c2 = list(w)
c3 = copy.copy(w)
c4 = copy.deepcopy(w)
c5 = [e for e in w]

c6 = []
for e in w:
    c6.append(e)
    
c7 = []
c7.extend(w)

print c1, c2, c3, c4, c5, c6, c7
</pre>

<p>
We have a list of three strings. We make a copy of the list
seven times. 
</p>

<pre class="explanation">
import copy
</pre>

<p>
We import the <code>copy</code> module, which has two methods for copying.
</p>

<pre class="explanation">
c1 = w[:]
</pre>

<p>
A list is copied using the slice syntax.
</p>

<pre class="explanation">
c2 = list(w)
</pre>

<p>
The <code>list()</code> function creates a copy of a list, when it takes
a list as a parameter. 
</p>

<pre class="explanation">
c3 = copy.copy(w)
c4 = copy.deepcopy(w)
</pre>

<p>
The <code>copy()</code> method produces a shallow copy of a list. The
<code>deepcopy</code> produces a deep copy of a list. 
</p>

<pre class="explanation">
c5 = [e for e in w]
</pre>

<p>
A copy of a string is created using list comprehension.
</p>

<pre class="explanation">
c6 = []
for e in w:
    c6.append(e)
</pre>

<p>
A copy created by a for loop.
</p>

<pre class="explanation">
c7 = []
c7.extend(w)
</pre>

<p>
The <code>extend</code> method can be used to create a copy
too.
</p>


<pre>
$ ./copying.py
['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] 
['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] ['Python', 'Ruby', 'Perl'] 
['Python', 'Ruby', 'Perl']
</pre>

<p>
Seven copies of a string list were created.
</p>


<h2>Indexing list elements</h2>

<p>
Elements in a Python list can be accessed by their index. Index
numbers are integers; they start from zero. Indexes can be negative; they
refer to elements from the end of the list. The first item in a list has index 0,
the last item has -1. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

print n[0]
print n[-1]
print n[-2]

print n[3]
print n[5]
</pre>

<p>
We can access an element of a list by its index. The index is placed between the
square brackets [] after the name of the list. 
</p>

<pre class="explanation">
print n[0]
print n[-1]
print n[-2]
</pre>

<p>
These three lines print the first, the last and the last but one item of the 
list. 
</p>

<pre class="explanation">
print n[3]
print n[5]
</pre>

<p>
The two lines print the fourth and sixth element of the list. 
</p>

<pre>
$ ./indexing.py
1
8
7
4
6
</pre>

<p>
Example output.
</p>

<hr class="btm">

<p>
The <code>index(e, start, end)</code> method looks for a particular element and
returns its lowest index. The start and end are optional parameters, that limit the
search to given boundaries. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 1, 2, 3, 1, 2]

print n.index(1)
print n.index(2)

print n.index(1, 1)
print n.index(2, 2)

print n.index(1, 2, 5)
print n.index(3, 4, 8)
</pre>

<p>
A code example with the <code>index()</code> method.
</p>

<pre class="explanation">
print n.index(1)
print n.index(2)
</pre>

<p>
These two lines print the indexes of the leftmost 1, 2 values of
the n list. 
</p>

<pre class="explanation">
print n.index(1, 1)
print n.index(2, 2)
</pre>

<p>
Here we search for 1, 2, numbers after specified indexes. 
</p>

<pre class="explanation">
print n.index(1, 2, 5)
</pre>

<p>
Finally, we search for value 1 between values with indexes
2-5. 
</p>

<pre>
$ ./indexing2.py
0
1
4
5
4
6
</pre>

<p>
Example output.
</p>


<h2>Slicing</h2>

<p>
List slicing is an operation that extracts certain 
elements from a list and forms them into another list. Possibly with 
different number of indices and different index ranges.
</p>

<p>
The syntax for list slicing is as follows:
</p>

<pre>
[start:end:step]
</pre>

<p>
The start, end, step parts of the syntax are integers. Each of them is optional.
They can be both positive and negative. The value having the end index is not 
included in the slice. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

print n[1:5]
print n[:5]
print n[1:]
print n[:]
</pre>

<p>
We create four slices from a list of 8 integers. 
</p>

<pre class="explanation">
print n[1:5]
</pre>

<p>
The first slice has values with indexes 1, 2, 3 and 4. 
The newly formed list is [2, 3, 4, 5].
</p>

<pre class="explanation">
print n[:5]
</pre>

<p>
If the start index is omitted then a default value is assumed, which is 0.
The slice is [1, 2, 3, 4, 5].
</p>

<pre class="explanation">
print n[1:]
</pre>

<p>
If the end index is omitted, the -1 default value is taken. In such a case a 
slice takes all values to the end of the list. 
</p>

<pre class="explanation">
print n[:]
</pre>

<p>
Even both indexes can be left out. This syntax creates a copy of a list. 
</p>

<pre>
$ ./slice.py
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
</pre>

<p>
Output of the example.
</p>

<hr class="btm">

<p>
The third index in a slice syntax is the step. It allows us to take every
n-th value from a list. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

print n[1:9:2]
print n[::2]
print n[::1]
print n[1::3]
</pre>

<p>
We form four new lists using the step value. 
</p>

<pre class="explanation">
print n[1:9:2]
</pre>

<p>
Here we create a slice having every second element from the n list, starting from
the second element, ending in the eighth element. The new list has [2, 4, 6, 8]
elements.
</p>

<pre class="explanation">
print n[::2]
</pre>

<p>
Here we build a slice by taking every second value from the beginning to the end
of the list. 
</p>

<pre class="explanation">
print n[::1]
</pre>

<p>
This creates a copy of a list. 
</p>

<pre class="explanation">
print n[1::3]
</pre>

<p>
The slice has every third element from the second element to the end of the
n list. 
</p>

<pre>
$ ./slice2.py
[2, 4, 6, 8]
[1, 3, 5, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 5, 8]
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
Indexes can be negative numbers. Negative indexes refer to values from the end
of the list. The last element has index -1, the last but one has index -2 etc.
Indexes with lower negative numbers must come first in the syntax. This means
that we write [-6, -2] instead of [-2, -6]. The latter returns an empty list. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

print n[-4:-1]
print n[-1:-4]

print n[-5:]
print n[-6:-2:2]
print n[::-1]
</pre>

<p>
In this script, we form five lists. We also use negative index numbers.
</p>

<pre class="explanation">
print n[-4:-1]
print n[-1:-4]
</pre>

<p>
The first line returns [5, 6, 7], the second line returns an empty list.
Lower indexes must come before higher indexes.
</p>

<pre class="explanation">
print n[::-1]
</pre>

<p>
This creates a reversed list.
</p>

<pre>
$ ./slice3.py
[5, 6, 7]
[]
[4, 5, 6, 7, 8]
[3, 5]
[8, 7, 6, 5, 4, 3, 2, 1]
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
The above mentioned syntax can be used in assignments. There must be an
iterable on the right side of the assignment. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5, 6, 7, 8]

n[0] = 10
n[1:3] = 20, 30
n[3::1] = 40, 50, 60, 70, 80
print n
</pre>

<p>
We have a list of 8 integers. We use the slice syntax to replace the elements
with new values. 
</p>


<h2>Traversing lists</h2>

<p>
This section will point out three basic ways to traverse a list in Python.
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

for e in n:
    print e,
    
print   
</pre>

<p>
The first one is the most straightforward way to traverse a list.
</p>

<pre class="explanation">
n = [1, 2, 3, 4, 5]
</pre>

<p>
We have a numberical list. There are five integers in the list.
</p>

<pre class="explanation">
for e in n:
    print e,
</pre>

<p>
Using the <code>for</code> loop, we go through the list one by one
and print the current element to the console. 
</p>


<pre>
$ ./traverse.py
1 2 3 4 5
</pre>

<p>
This is the output of the script. The integers are printed to the 
terminal. 
</p>

<hr class="btm">

<p>
The second example is a bit more verbose.
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

i = 0
s = len(n)

while i &lt; s:
    print n[i],
    i = i + 1

print   
</pre>

<p>
We are traversing the list using the <code>while</code> loop.
</p>

<pre class="explanation">
i = 0
l = len(n)
</pre>

<p>
First we need to define a counter and find out the size of the list. 
</p>

<pre class="explanation">
while i &lt; s:
    print n[i],
    i = i + 1
</pre>

<p>
With the help of these two numbers, we go through the list and
print each element to the terminal. 
</p>

<hr class="btm">

<p>
The <code>enumerate()</code> built-in function gives us both the
index and the value of a list in a loop.  
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 2, 3, 4, 5]

for e, i in enumerate(n):
    print "n[%d] = %d" % (e, i)
</pre>

<p>
In the example, we print the values and
the indexes of the values.
</p>

<pre>
$ ./traverse3.py 
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5
</pre>

<p>
Running the script.
</p>


<h2>Counting list elements</h2>

<p>
Sometimes it is important to count list elements. How
many times they are present in the Python list. 
The <code>count()</code> method is suited for this. 
</p>

<pre class="code">
#!/usr/bin/python

n = [1, 1, 2, 3, 4, 4, 4, 5]

print n.count(4)
print n.count(1)
print n.count(2)
print n.count(6)
</pre>

<p>
In this example, we count the number of occurences of a few numbers
in the n list. 
</p>

<pre class="explanation">
n = [1, 1, 2, 3, 4, 4, 4, 5]
</pre>

<p>
We have a list of integer numbers. 1, 4 integers are present multiple times.
</p>

<pre class="explanation">
print n.count(4)
print n.count(1)
print n.count(2)
print n.count(6)
</pre>

<p>
Using the <code>count()</code> method, we find out the occurence of 4, 1, 2, 6
numbers.
</p>


<pre>
$ ./counting.py
3
2
1
0
</pre>

<p>
Script output. Number 4 is present 3 times, 1 twice, 2 once and 6 is not present
in the list. 
</p>


<h2>Nested lists</h2>

<p>
It is possible to nest lists into another lists. With a nested list a new
dimension is created. To access nested lists one needs additional square 
brackets []. 
</p>

<pre class="code">
#!/usr/bin/python

nums = [[1, 2], [3, 4], [5, 6]]

print nums[0]
print nums[1]
print nums[2]

print nums[0][0]
print nums[0][1]

print nums[1][0]
print nums[2][1]

print len(nums)
</pre>

<p>
In the example, we have three nested lists having two elements each. 
</p>

<pre class="explanation">
print nums[0]
print nums[1]
print nums[2]
</pre>

<p>
Three nested lists of the nums list are printed to the console.
</p>

<pre class="explanation">
print nums[0][0]
print nums[0][1]
</pre>

<p>
Here we print the two elements of the first nested list. The nums[0] refers
to the first nested list; the nums[0][0] refers to the first element of the
first nested list, namely 1. 
</p>

<pre class="explanation">
print len(nums)
</pre>

<p>
The line prints 3. Each nested list is counted as one element. Its inner elements
are not taken into account. 
</p>

<pre>
$ ./multi.py
[1, 2]
[3, 4]
[5, 6]
1
2
3
6
3
</pre>

<p>
Example output. 
</p>

<hr class="btm">

<p>
The second example has additional dimensions. 
</p>

<pre class="code">
#!/usr/bin/python

nums = [[1, 2, [3, 4, [5, 6]]]]

print nums[0]
print nums[0][2]
print nums[0][2][2]

print nums[0][0]
print nums[0][2][1]
print nums[0][2][2][0]
</pre>

<p>
In the example, the [5, 6] list is nested into [3, 4, ...] list, the
[3, 4, [4, 6]] is nested into the [1, 2, ...] list which is finally an
element of the nums list. 
</p>

<pre class="explanation">
print nums[0]
print nums[0][2]
print nums[0][2][2]
</pre>

<p>
These three lines print the nested lists to the console. 
</p>

<pre class="explanation">
print nums[0][0]
print nums[0][2][1]
print nums[0][2][2][0]
</pre>

<p>
Here three elements are accessed. Additional brackets [] are needed
when referring to inner lists. 
</p>

<pre>
$ ./multi2.py
[1, 2, [3, 4, [5, 6]]]
[3, 4, [5, 6]]
[5, 6]
1
4
5
</pre>

<p>
Example output.
</p>


<h2>Sorting lists</h2>

<p>
In this section we will sort list elements. Python has a built-in 
list method <code>sort()</code> and <code>sorted()</code> function
for doing sorting.
</p>

<pre class="code">
#!/usr/bin/python

n = [3, 4, 7, 1, 2, 8, 9, 5, 6]
print n

n.sort()
print n

n.sort(reverse=True)
print n
</pre>

<p>
In the code example, we have a list of unsorted integers. 
We sort the elements using the <code>sort()</code> method.
The method sorts the elements in-place; the original list 
is modified.
</p>

<pre class="explanation">
n.sort()
</pre>

<p>
The <code>sort()</code> method sorts the elements in ascending order. 
</p>

<pre class="explanation">
n.sort(reverse=True)
</pre>

<p>
With the reverse parameter set to True, the list is sorted in a descending
order. 
</p>

<pre>
$ ./sort.py
[3, 4, 7, 1, 2, 8, 9, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
</pre>

<p>
In the ouput we can see the original list, the sorted list in ascending
and descending orders. 
</p>

<hr class="btm">

<p>
If we do not want to change the original list, we can use the
<code>sorted</code> function. This function creates a new
sorted list. 
</p>

<pre class="code">
#!/usr/bin/python

n = [3, 4, 1, 7, 2, 5, 8, 6]

print n
print sorted(n)
print n
</pre>

<p>
In the example, we use the <code>sorted()</code> function
to sort the elements of a list. 
</p>

<pre>
$ ./sort2.py
[3, 4, 1, 7, 2, 5, 8, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 1, 7, 2, 5, 8, 6]
</pre>

<p>
From the ouput of the script we can see, that the original
list is not modified. 
</p>

<hr class="btm">

<p>
We need to do additional work if we want to 
sort unicode strings. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

import locale
from functools import cmp_to_key

w = [u'zem', u'štebot', u'rum', u'železo', u'prameň', u"sob"]
locale.setlocale(locale.LC_COLLATE, ('sk_SK', 'UTF8'))

w.sort(key=cmp_to_key(locale.strcoll))

for e in w:
    print e
</pre>

<p>
We have a list of six unicode strings. We change the locale settings
to sort the strings according to current language option.
</p>

<pre class="explanation">
import locale
from functools import cmp_to_key
</pre>

<p>
We import the <code>locale</code> module and the <code>cmp_to_key</code> conversion
function.
</p>

<pre class="explanation">
w = [u'zem', u'štebot', u'rum', u'železo', u'prameň', u"sob"]
</pre>

<p>
This is a list of six strings. The strings are in Slovak language and have
some diacritical marks. They play role in sorting the characters correctly.
</p>

<pre class="explanation">
locale.setlocale(locale.LC_COLLATE, ('sk_SK', 'UTF8'))
</pre>

<p>
We set the locale lettings for the Slovak language.
</p>

<pre class="explanation">
w.sort(key=cmp_to_key(locale.strcoll))
</pre>

<p>
We sort the list. The locale.strcoll compares two strings according 
to the current LC_COLLATE setting. The cmp_to_key function transform an old-style 
comparison function to a key-function. 
</p>

<pre class="explanation">
for e in w:
    print e
</pre>

<p>
We print the sorted words to the console. 
</p>


<pre>
$ ./sort_locale.py
prameň
rum
sob
štebot
zem
železo
</pre>

<p>
The elements were correctly sorted. The specifics of the Slovak 
alphabet were taken into account. 
</p>

<h2>Reversing elements</h2>

<p>
We can reverse elements in a list in a few ways in Python.
Reversing elements should not be confused with sorting in a 
reverse way. 
</p>

<pre class="code">
#!/usr/bin/python

a1 = ["bear", "lion", "tiger", "eagle"]
a2 = ["bear", "lion", "tiger", "eagle"]
a3 = ["bear", "lion", "tiger", "eagle"]

a1.reverse()
print a1

it = reversed(a2)
r = list()
for e in it:
    r.append(e)
print r

print a3[::-1]
</pre>

<p>
In the example, we have three identical string lists. 
We reverse the elements in three ways.
</p>

<pre class="explanation">
a1.reverse()
</pre>

<p>
The first way is to use the <code>reverse()</code> method.
</p>

<pre class="explanation">
it = reversed(a2)
r = list()
for e in it:
    r.append(e)
print r
</pre>

<p>
The <code>reversed()</code> function returns a reverse iterator. 
We use the iterator in a for loop and create a new reversed list. 
</p>

<pre class="explanation">
print a3[::-1]
</pre>

<p>
The third way is to reverse the list using the slice syntax, where the 
step parameter is set to -1. 
</p>


<pre>
$ ./reverse.py
['eagle', 'tiger', 'lion', 'bear']
['eagle', 'tiger', 'lion', 'bear']
['eagle', 'tiger', 'lion', 'bear']
</pre>

<p>
All the three lists were reversed OK.
</p>


<h2>List comprehensions</h2>

<p>
A <b>list comprehension</b> is a syntactic construct which creates a list based on 
existing list. The syntax was influenced by mathematical notation of sets. The Python
syntax was inspired by the Haskell programming language. 
</p>

<pre>
L = [expression for variable in sequence [if condition]]
</pre>

<p>
The above pseudo code shows the syntax of a list comprehension. A list comprehension
creates a new list. It is based on an existing list. A for loop goes through the
sequence. For each loop an expression is evaluated if the condition is met. If
the value is computed it is appended to the new list. 
</p>

<p>
List comprehensions provide a more concise way to create lists in situations 
where <code>map()</code> and <code>filter()</code> and/or nested loops could be used.
</p>

<pre class="code">
#!/usr/bin/python

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

b = [e for e in a if e % 2]
print b
</pre>

<p>
In the example we have defined a list of numbers.
With the help of the list comprehension, we create a new list
of numbers that cannot be divided by 2 without a remainder.
</p>

<pre class="explanation">
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>

<p>
This is the list of 9 integers. 
</p>

<pre class="explanation">
b = [e for e in a if e % 2]
</pre>

<p>
Here we have the list comprehension. In the <code>for e in a</code> loop
each element of a list is taken. Then a <code>if e % 2</code> condition
is tested. If the condition is met, an expression is evaluated. In our
case the expression is a pure <code>e</code> which takes the element as
it is. Finally the element is appended to the list. 
</p>


<pre>
$ ./list_comprehension.py
[1, 3, 5, 7, 9]
</pre>

<p>
Example output. The numbers in a list cannot be divided by 2, without a
remainder. 
</p>

<hr class="btm">

<p>
In the second example we compare a list comprehension to a traditional
for loop.
</p>

<pre class="code">
#!/usr/bin/python

lang = "Python"

a = []
for e in lang:
    a.append(ord(e))

b = [ord(e) for e in lang]

print a
print b
</pre>

<p>
In the example we have a string. We want to create a
list of the ASCII integer codes of the letters of the string.
</p>

<pre class="explanation">
a = []
for e in lang:
    a.append(ord(e))
</pre>

<p>
We create such a list with the for loop.
</p>

<pre class="explanation">
b = [ord(e) for e in lang]
</pre>

<p>
Here the same is produced using a list comprehension. 
Note that the if condition was omitted. It is optional. 
</p>

<pre>
$ ./list_comprehension2.py
[80, 121, 116, 104, 111, 110]
[80, 121, 116, 104, 111, 110]
</pre>

<p>
Example output.
</p>


<h2>The map() and filter() functions</h2>

<p>
The <code>map()</code> and <code>filter()</code> functions are mass functions that
work on all list items. They are part of the functional programming built into the 
Python language. 
</p>

<p>
Today it is recommended to use list comprehensions instead of these functions where
possible.
</p>


<pre class="code">
#!/usr/bin/python


def to_upper(s):
    return s.upper()

words = ["stone", "cloud", "dream", "sky"]

words2 = map(to_upper, words)
print words2
</pre>

<p>
The <code>map()</code> function applies a particular function to every
element of a list. 
</p>

<pre class="explanation">
def to_upper(s):
    return s.upper()
</pre>

<p>
This is the definition of the function, that will be applied to every 
list element. It calls the <code>upper()</code> string method on a given string.
</p>

<pre class="explanation">
words = ["stone", "cloud", "dream", "sky"]
</pre>

<p>
This is the list of strings. 
</p>

<pre class="explanation">
words2 = map(to_upper, words)
print words2
</pre>

<p>
The <code>map()</code> function applies the <code>to_upper()</code> function to 
every string element of the words list. A new list is formed and
returned back. We print it to the console. 
</p>

<pre>
$ ./map.py
['STONE', 'CLOUD', 'DREAM', 'SKY']
</pre>

<p>
Every item of the list is in capital letters. 
</p>

<hr class="btm">

<p>
The <code>filter()</code> function constructs a list from those elements of 
the list for which a function returns true.
</p>

<pre class="code">
#!/usr/bin/python


def positive(x):
    return x > 0

n = [-2, 0, 1, 2, -3, 4, 4, -1]

print filter(positive, n)
</pre>

<p>
An example demonstrating the <code>filter()</code> function. It will 
create a new list having only positive values. It will filter out all negative
values and 0.
</p>

<pre class="explanation">
def positive(x):
    return x > 0
</pre>

<p>
This is the definition of the function used by the <code>filter()</code>
function. It returns True or False. Functions that return a boolean value
are called <b>predicates</b>.
</p>

<pre>
$ ./filter.py
[1, 2, 4, 4]
</pre>

<p>
Output of the filter.py script. 
</p>

<p>
In this part of the Python tutorial, we have described Python
lists.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span>  ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 27, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

